<?php
/** 
 * Created by RisingSun. 
 * User: MarkSpace 
 * Date: 20210822
 * Time: 11:05 
 * 列表管理
 */
namespace app\product\model;

use  app\product\model\Model;
use  Mscore\Core\Redis;

class Daycontrol extends Model{
    
    private $operate = 'pro_dayoperate';
    private $risk = 'pro_dayrisk';
    private $hashfix;

    private $orderlog = 'pro_dayorderlog';
    private $account = 'user_account';
    private $order = 'pro_dayorder';
    private $autorule = 'pro_dayrule';
    

    /**
     * 初始化自动连接方法
     * @param array $__construct 
     * @param array $where 
    */
    public function __construct()  
    {    
        $this->hashfix=config('redis.redis_db.db_hashfix');
    }

    /**
     * 列表
     * @param array $list 
     * @param array $where 
     */ 
    public function list($where=null,$page=1,$page_size=10){
        //矿机列表
        $list['datalist']= Model::name($this->operate)
            ->alias('a')
            ->field('a.*')
            ->where($where)
            ->limit(($page-1)*$page_size,$page_size)
            ->order('a.aid asc, a.id desc')
            ->select();
        //数据总数
        $list['total']=Model::name($this->operate)
            ->alias('a')
            ->where($where)
            ->count('id');
        return $list;
    }

    /**
     * 添加
     * @param array $info 
     * @param array $where 
     */ 
    public function info($id=null,$field='*'){  
        $info=Model::name($this->operate)
           ->field($field)
           ->where(['id'=>$id])
           ->find();
        return  $info;
    }

    /**
     * 添加
     * @param array $info 
     * @param array $where 
     */ 
    public function suminfo($where=null,$field='*'){  
        $info=Model::name($this->order)
           ->alias('a')
           ->field($field)
           ->where($where)
           ->find();
        return  $info;
    }

    /**
     * 保存
     * @param array $save 
     * @param array $where 
     */ 
    public function save($data=[]){

        $data  = [
            'id'=>$data['id'],
            'title'=>$data['title'],
            'aid'=>$data['aid'],
            'username'=>$data['aid']>0?$data['username']:'platform(平台)',
            'proid'=>$data['proid'],
            'conuts'=>isset($data['conuts'])?$data['conuts']:20,
            'description'=>$data['description'],
            'auto'=>$data['auto'],
            'status'=>$data['status'],
            'fixmoney'=>$data['fixmoney'],
            'fixtime'=>$data['fixtime'],
            'relate'=>$data['auto']==1?$data['relate']:0,
            'relatename'=>isset($data['relatename'])&&!empty($data['relatename'])?$data['relatename']:$data['title'],
            'updatetime'=>date('Y-m-d H:i:s',time())
        ];
        switch (true) {
            case isset($data['id'])&&!empty($data['id']):
                Model::name($this->operate)->where('id=' . $data['id'])->update($data);
                return  $data['id'];
                break;
            
            default:
                unset($data['id']);
                $id = Model::name($this->operate)->insertGetId($data);
                return $id;
                break;
        }
        return false;
    }

    /**
     * 添加
     * @param array $info 
     * @param array $where 
     */ 
    public function setorder($id=0,$data=[]){
        if(!empty($id)){
            $data  = [
                'win'=>$data['win']
            ];
            Model::name($this->order)->where('id=' . $id)->update($data);
            return  true;
        }
        return  false;
    }

    /**
     * 删除
     * @param array $del 
     * @param array $where 
     */
    public function del($id=null){
     //删除
        if ($id) {
            Model::name($this->operate)->where('id='.$id)->delete();
            return true;
        }
        return false;
    }

    /**
     * 获取disk
     * @param array $disk 
     * @param array $where 
     */ 
    public function disk($where='',$field='*'){
       return Model::name($this->risk)
           ->field($field)
           ->where($where)
           ->order('status asc, id asc')
           ->select()
           ->toArray();
    }

    /**
     * 列表
     * @param array $list 
     * @param array $where 
     */ 
    public function disklist($where=null,$page=1,$page_size=10){
        //矿机列表
        $list['datalist']= Model::name($this->risk)
            ->alias('a')
            ->field('a.*')
            ->where($where)
            ->limit(($page-1)*$page_size,$page_size)
            ->order('a.status asc, a.id asc')
            ->select()
            ->toArray();
        //数据总数
        $list['total']=Model::name($this->risk)
            ->alias('a')
            ->where($where)
            ->count('id');
        return $list;
    }
    
    /**
     * 获取diskorder
     * @param array $disk 
     * @param array $where 
     */ 
    public function countorder($where=''){
       return Model::name($this->order)
           ->where($where)
           ->count('id');
    }

    /**
     * 获取disk
     * @param array $diskinfo
     * @param array $where 
     */ 
    public function diskinfo($where='',$field='*'){
       return Model::name($this->risk)
           ->field($field)
           ->where($where)
           ->find();
    }

    /**
     * 获取disk
     * @param array $diskinfo
     * @param array $where 
     */ 
    public function savediskinfo($data=[]){
        switch (true) {
            case isset($data['id'])&&!empty($data['id']):
                $content = [
                        'win'=>$data['win']
                ];
                Model::name($this->risk)->where('id='.$data['id'])->update($content);
                return true;
                break;
            default:
                break;
        }
        return false;
    }

    /**
     * 保存
     * @param array $savedisk 
     * @param array $where 
     */ 
    public function savedisk($data=[]){
        switch (true) {
            case !empty($data):
                $disk=Model::name($this->risk)->where('operate_id='.$data['operate_id'].' and status<2')->order('id desc')->field('sn,endtime')->find();
                if (empty($disk['sn']) || empty($disk['endtime'])){
                    $key = config('daycontrol.key','/config/day');
                    $hashfix = config('redis.redis_db.db_hashfix');
                    $info = Redis::exec('get',[$hashfix.$key]);
                    $info = json_decode($info,true);
                    $sn = $info['acode'];
                    $endtime = $info['endtime'];
                    $timelong = $info['timelong'];
                    unset($info,$disk);
                }
                $sn=(intval($sn)+1);
                $endtime = intval($endtime)+intval($timelong);
                Model::startTrans();
                try {
                    if(isset($data['conuts'])&&!empty($data['conuts'])){
                        for ($i=0; $i < $data['conuts']; $i++) { 
                            $content = [
                                'aid'=>isset($data['aid'])&&!empty($data['aid'])?$data['aid']:0,
                                'sn'=>(intval($sn)+$i),
                                'title'=>$data['title'],
                                'operate_id'=>$data['operate_id'],
                                'win'=>rand(1,2),
                                'proid'=>$data['proid'],
                                'endtime'=>(intval($endtime)+intval($timelong)*$i-1)
                            ];
                            Model::name($this->risk)->insert($content);
                        }    
                    }
                    $conuts=Model::name($this->risk)->where('operate_id='.$data['operate_id'])->count('id');
                    Model::name($this->operate)->where('id='.$data['operate_id'])->update(['conuts'=>$conuts]);
                    Model::commit();
                    return true;
                } catch (Exception $e) {
                    Model::rollback();
                    $errmsg = [ 'errcode'=>$e->getCode(), 'message'=>$e->getMessage(), 'file'=>$e->getFile(), 'line'=>$e->getLine(), 'backtrace'=>getTraceAsString(),'error'=>__toString()];
                    $errmsg = json_encode($errmsg,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES)."\r\n";
                    errlog($errmsg);
                    return false;
                }
                break;
            default:
                return false;
                break;
        }
        return false;
    }

    /**
     * 删除disk
     * @param array $disk 
     * @param array $where 
     */ 
    public function deldisk($where=''){
       if ($where) {
            Model::name($this->risk)->where($where)->delete();
            return true;
        }
        return false;
    }

    /**
     * 更新运营
     * @param array $disk 
     * @param array $where 
     */ 
    public function operatesave($where='',$data=[]){
       if ($where) {
            Model::name($this->operate)->where($where)->update($data);
            return true;
        }
        return false;
    }

    /**
     * 操作redis
     * @param array $writeRedis
     * @param array $where $page $num
     */
    public function execRedis($meth,$arr,$db='0')
    {
        if($meth){
            $arr[0]=$this->hashfix.$arr[0];
            $data = Redis::exec($meth,$arr,$db);
            return $data;
        }        
        return false;
    }

    /**
     * 列表
     * @param array $list 
     * @param array $where 
     */ 
    public function orderlist($where=null,$page=1,$page_size=10){
        //矿机列表
        $list['datalist']= Model::name($this->order)
            ->alias('a')
            ->join($this->account.' b','a.aid=b.aid','left')
            ->field('a.*, b.username, b.realname')
            ->where($where)
            ->limit(($page-1)*$page_size,$page_size)
            ->order('a.aid asc, a.id desc')
            ->select()
            ->toArray();
        //数据总数
        $list['total']=Model::name($this->order)
            ->alias('a')
            ->where($where)
            ->count('id');
        return $list;
    }
    
    /**
     * 清空数据表
     * @param array $cleardata 
     */ 
    public function cleardata(){
        Model::execute('TRUNCATE TABLE ms_'.$this->risk);
        return true;
    }

    /**
     * 规则信息
     * @param array $ruleinfo 
     * @param array $where 
     */ 
    public function ruleinfo($where=null){
        return Model::name($this->autorule)->where($where)->find();
    }

    /**
     * 保存
     * @param array $rulesave 
     * @param array $where 
     */ 
    public function rulesave($data=[]){
        $status=Model::name($this->autorule)->where('id=1')->find();
        if(!empty($status)){
            Model::name($this->autorule)->where('id=1')->update($data);
        }else{
            Model::name($this->autorule)->insert($data);
        }
        return true;
    }
    /**
     * 保存
     * @param array $save 
     * @param array $where 
     */ 
    public function rulesaveop($id,$auto=1){
        Model::name($this->operate)->where('id=' . $id)->update(['auto'=>$auto]);
        return  $id;
    }
}
